package org.redxentertainment.videomanager;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class VideoManagerCategory extends Activity implements OnClickListener, Runnable {

	private ArrayList<Video> 		videoArray;
	private ArrayList<Video> 		videoUpdateArray;
	private VideoAdapter 			videoAdapter;
	private ListView				videoView;
	private String					category;
	private Video					videoToDelete;
	
	private static final int MENU_PLAY	 		= 1;
	private static final int MENU_SHUFFLE 		= 2;
	private static final int MENU_CLEAR			= 3;

	private static final int CONTEXT_DELETE 	= 10;
	private static final int CONTEXT_ENQUEUE 	= 11;
	private static final int CONTEXT_DETAILS 	= 12;
	
	private static final int MSG_ADD_TO_LIST	= 1;
	private static final int MSG_UPDATE_LIST	= 2;
	private static final int MSG_SORT_LIST		= 3;
	private static final int MSG_NOVID_ERR		= 4;
	private static final int MSG_NOSTOR_ERR		= 5;
	private static final int MSG_LIST_COMPLETE	= 6;
	private static final int MSG_THREAD_ERR		= 7;
	private static final int MSG_UPDATE_THUMB 	= 8;
	private static final int MSG_UPDATE_THUMBS 	= 9;
	
	//-------------------------------------------------------------------------------------
	private Handler messageHandler = new Handler() {

		public void handleMessage(Message msg) {  
			Builder builder;
			
			switch(msg.what) {
				case MSG_UPDATE_LIST:
					videoAdapter.notifyDataSetChanged();
					videoAdapter.setNotifyOnChange(false);
					break;
					
				case MSG_UPDATE_THUMB:
					videoAdapter.remove( (Video) msg.obj );
					videoAdapter.insert((Video) msg.obj, msg.arg1);
					break;
					
				case MSG_UPDATE_THUMBS:
					videoAdapter.videos = videoUpdateArray;
					videoAdapter.notifyDataSetChanged();
					break;
					
				case MSG_ADD_TO_LIST:
					videoAdapter.add( (Video)msg.obj );
					break;
					
				case MSG_SORT_LIST:
					//videoAdapter.sort(compareVideos);
					break;
					
				case MSG_LIST_COMPLETE:
					if( category.equals("All Videos") ) {
			        	videoView.setFastScrollEnabled(true);
			        }
					
					videoAdapter.notifyDataSetChanged();
					break;
					
				case MSG_NOVID_ERR:
		        	builder = new AlertDialog.Builder(org.redxentertainment.videomanager.VideoManagerCategory.this);
					builder.setTitle("Status");
					builder.setMessage("No video files found!");
					builder.setNeutralButton("ok", null);
					builder.show();
					break;
					
				case MSG_NOSTOR_ERR:
					builder = new AlertDialog.Builder(org.redxentertainment.videomanager.VideoManagerCategory.this);
					builder.setTitle("Error!");
					builder.setMessage("Can not access video store!");
					builder.setNeutralButton("ok", null);
					builder.show();
					break;
					
				case MSG_THREAD_ERR:
					builder = new AlertDialog.Builder(org.redxentertainment.videomanager.VideoManagerCategory.this);
					builder.setTitle("Thread Error!");
					builder.setMessage("Cursor closed unexpectedly!");
					builder.setNegativeButton("ok", null);
					builder.show();
					break;
					
			}
		}
	};
	
	/*
	Comparator<Video> compareVideos = new Comparator<Video>() {
		//@Override
		public int compare(Video a, Video b) {
			if(a.sortOrder < b.sortOrder) {
				return -1;
			} else {
				return 1;
			}
		}
	};
	*/
	
	//-------------------------------------------------------------------------------------
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video_list);

        Bundle 		extras 	= getIntent().getExtras();
        
        category = extras.getString("category");
        
        videoArray 			= new ArrayList<Video>();
        videoUpdateArray 	= new ArrayList<Video>();
        videoView 			= (ListView)findViewById(R.id.videoList);
        videoAdapter 		= new VideoAdapter(getApplicationContext(), R.layout.video, videoArray);
        
        videoView.setAdapter(videoAdapter);
    }
    
    //-------------------------------------------------------------------------------------
    @Override
    public void onStart() {
        super.onStart();
        
        setTitle(category);
        
        videoAdapter.clear();
        populate();
        
        videoView.setOnItemClickListener(clickListener);
        videoView.setOnCreateContextMenuListener(this);
        
        Thread thread = new Thread( (Runnable)this );
        thread.start();
    }
    
    //-------------------------------------------------------------------------------------
    @Override
    public void onDestroy() {
        super.onDestroy();
        
    }
    
    //-------------------------------------------------------------------------------------
    @Override
    public void onStop() {
        super.onStop();
    }
    
    //-------------------------------------------------------------------------------------
    @Override
    public void  onSaveInstanceState  (Bundle  icicle) {
    	
    }
    
    //-------------------------------------------------------------------------------------
    private OnItemClickListener clickListener = new OnItemClickListener() {
    	//@Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long index) {
        	Video video = videoAdapter.getItem((int)index);
        	
        	playVideo(video.id);        
        }
    };
    
    //-------------------------------------------------------------------------------------
    private void playVideo (long id) {
    	Uri				videoUri 	= Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, ""+ id);
    	Intent 			videoPlayer = new Intent(Intent.ACTION_VIEW, videoUri);
    	VideoDatabase 	videoDB 	= new VideoDatabase(getBaseContext());
    	
    	videoDB.setVideoWatched(id);
    	videoDB.close();
    	startActivity(videoPlayer);
    }
    
    //-------------------------------------------------------------------------------------
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) 
    {
         super.onCreateContextMenu(menu, view, menuInfo);
         menu.add(0, CONTEXT_DELETE, 0, "Delete File");
         
         menu.add(0, CONTEXT_ENQUEUE, 0, "Add to Queue");
         
         menu.add(0, CONTEXT_DETAILS, 0, "View Details");
         
         menu.setHeaderTitle("Options");
    }
 	
    //-------------------------------------------------------------------------------------
    public boolean onContextItemSelected(MenuItem item)
    {   
    	Video 			video;
    	VideoDatabase 	videoDB 					= new VideoDatabase( getBaseContext() );
    	AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
    	
    	video = videoAdapter.getItem(menuInfo.position);
    	
    	switch (item.getItemId()) {
        	case CONTEXT_DELETE:
        		videoToDelete = video;
        		
        		Builder builder = new AlertDialog.Builder(this);
    			builder.setTitle("Comfirm");
    			builder.setMessage("Delete video?");
    			builder.setPositiveButton("Yes", this);
    			builder.setNegativeButton("No", this);
    			builder.show();
        		break;
        		
        	case CONTEXT_ENQUEUE:
        		videoDB.enqueue(video.id);
        		videoAdapter.remove(video);
        		video.isQueued = true;
				videoAdapter.insert(video, menuInfo.position);
        		videoAdapter.notifyDataSetChanged();
        		break;
        		
        	case CONTEXT_DETAILS:
        		Intent categoryIntent = new Intent(getBaseContext(), org.redxentertainment.videomanager.VideoManagerDetails.class);
            	categoryIntent.putExtra("name", video.title);
            	categoryIntent.putExtra("category", video.album);
            	categoryIntent.putExtra("size", video.size);
            	categoryIntent.putExtra("path", video.path);
            	categoryIntent.putExtra("id", video.id);
            	startActivity(categoryIntent);  
        		break;
    	}
        return true;
    }
    
    //-------------------------------------------------------------------------------------
    public boolean onCreateOptionsMenu(Menu menu) {
      
        menu.add(0, MENU_CLEAR, 	0, "Clear Queue");
    		//.setIcon(R.drawable.clear);
      
        menu.add(0, MENU_SHUFFLE, 	0, "Play Queue (Shuffle)");
			//.setIcon(R.drawable.shuffle);
        
        menu.add(0, MENU_PLAY, 	0, "Play Queue");
			//.setIcon(R.drawable.play);
                
        return true;
    }
	
    //-------------------------------------------------------------------------------------
    public boolean onOptionsItemSelected(MenuItem item) {
    	VideoDatabase videoDB = new VideoDatabase( getBaseContext() );
    	long id;
    	Intent thisIntent;
    	
        switch (item.getItemId()) {
	        case MENU_SHUFFLE:
	        	id = videoDB.dequeueRandom();
	        	while( id != 0) {
	        		playVideo( id );
	        		id = videoDB.dequeueRandom();
	        	}
	        	break;
	        	
	        case MENU_CLEAR:
	        	videoDB.clearQueue();
	        	thisIntent = new Intent(org.redxentertainment.videomanager.VideoManagerCategory.this, org.redxentertainment.videomanager.VideoManagerCategory.class);
	        	thisIntent.putExtra("category", category);
            	startActivity(thisIntent);
            	finish();
	        	break;
	        	
	        case MENU_PLAY:       	
	        	id = videoDB.dequeue();
	        	while( id != 0) {
	        		playVideo( id );
	        		id = videoDB.dequeue();
	        	}
	        	break;
	        	
        }
        
        videoDB.close();
        return false;
    }

	//@Override
	public void onClick(DialogInterface dialog, int which) {
		File file;
		
		if(which == DialogInterface.BUTTON_POSITIVE) {
			getContentResolver().delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "_id=" + videoToDelete.id + "", null);
			file = new File(videoToDelete.path);
			file.delete();
			videoAdapter.remove(videoToDelete);
		} else if(which == DialogInterface.BUTTON_NEUTRAL) {
			finish();
		}
	}
	
	//-------------------------------------------------------------------------------------------------
	//-------------------------------------------------------------------------------------------------
	public void populate() {		
		String[] videoProjection = new String[] {
        		MediaStore.Video.Media.DISPLAY_NAME,
        		MediaStore.Video.Media.ARTIST,
        		MediaStore.Video.Media.ALBUM,
        		MediaStore.Video.Media.TITLE,
        		MediaStore.Video.Media.DURATION,
        		MediaStore.Video.Media.SIZE,
        		MediaStore.Video.Media.RESOLUTION,
        		MediaStore.Video.Media.BOOKMARK,
        		MediaStore.Video.Media.MIME_TYPE,
        		MediaStore.Video.Media._ID,
        		MediaStore.Video.Media.DATA
             };
        Video 				video;
        int 				size, duration;
        VideoDatabase 		videoDB 		= new VideoDatabase(getBaseContext());
        Cursor 				videoCursor;
        
        if(category.compareTo("All Videos") == 0) {
        	videoCursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoProjection, null, null, "_display_name");
        } else {
        	videoCursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoProjection, "album=\"" + category + "\"", null, "_display_name");
        }
        
        if(videoCursor == null) {
        	messageHandler.sendMessage(Message.obtain(messageHandler, MSG_NOSTOR_ERR));
        	return;
        }
        
        videoCursor.moveToFirst();
        while(! videoCursor.isAfterLast()  && ! videoCursor.isClosed() ) {
        	video 		= new Video();
        	
        	size 		= (videoCursor.getInt(5) / 1024) / 1024;
        	duration 	= videoCursor.getInt(4) / 60;
        	
        	video.mime 			= videoCursor.getString(7);
        	video.id 			= videoCursor.getLong(9);   	
        	video.title 		= videoCursor.getString(3);
        	video.path			= videoCursor.getString(10);
        	video.album 		= videoCursor.getString(2);
        	video.artist 		= videoCursor.getString(1);
        	video.duration		= duration;
        	video.size			= size;
        	video.wasWatched	= videoDB.videoWasWatched(video);
        		        	
        	if(duration != 0) {
        		video.description = duration + "Min, " + size + "MB";
        	} else {
        		video.description = size + "MB";
        	}
        	
        	videoAdapter.add(video);
        	videoDB.addVideo(video);
        	
        	videoCursor.moveToNext();
        }
        
        if( videoAdapter.isEmpty() ) {
        	messageHandler.sendMessage(Message.obtain(messageHandler, MSG_NOVID_ERR));
        }
        
        videoCursor.close();
        videoDB.close();
	}
	
	
	//-------------------------------------------------------------------------------------------------
	//-------------------------------------------------------------------------------------------------
	public void run() {		
		Video 					video;
		SharedPreferences 		preferences 	= getSharedPreferences("main", MODE_PRIVATE);
		BitmapFactory.Options 	options 		= new BitmapFactory.Options();
		int 					orientation 	= getResources().getConfiguration().orientation;
		
		if( orientation == Configuration.ORIENTATION_PORTRAIT ) {
			options.inSampleSize = 4;
		} else {
			options.inSampleSize = 2;
		}
    	
    	if( videoAdapter.isEmpty() ) {
        	return;
        }
    	
        for(int position=0; position<videoAdapter.getCount(); position++) {
        	video = videoAdapter.getItem(position);
        	
        	video.orientation = orientation;
        	
        	if( preferences.getBoolean("high-quality", true) ) {
	        	video.thumb 				= MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(), video.id, MediaStore.Video.Thumbnails.MINI_KIND, options);
	        	
	        	if(video.thumb != null) {
	        		if( video.orientation == Configuration.ORIENTATION_PORTRAIT ) {
	        			if( video.thumb.getHeight() > 115 ) {
	        				video.thumb = Bitmap.createBitmap(video.thumb, 0, 0, video.thumb.getWidth(), 115);
	    	    		}
	    	    		if( video.thumb.getWidth() >= 175 ) {
	    	    			video.thumb = Bitmap.createBitmap(video.thumb, 0, 0, 175, video.thumb.getHeight());
	    	    		}
	        		} else {
	        			if( video.thumb.getHeight() > 180 ) {
	        				video.thumb = Bitmap.createBitmap(video.thumb, 0, 0, video.thumb.getWidth(), 180);
	    	    		}
	    	    		if( video.thumb.getWidth() >= 280 ) {
	    	    			video.thumb = Bitmap.createBitmap(video.thumb, 0, 0, 280, video.thumb.getHeight());
	    	    		}
	        		}
	        	} else {
	        		options.inSampleSize 	= 1;
	        		video.thumb 			= MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(), video.id, MediaStore.Video.Thumbnails.MICRO_KIND, options);
	        	}
        	} else {
        		options.inSampleSize 	= 1;
        		video.thumb 			= MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(), video.id, MediaStore.Video.Thumbnails.MICRO_KIND, options);
        	}
        	
        	videoUpdateArray.add(video);
        	
        	//messageHandler.sendMessage( Message.obtain(messageHandler, MSG_UPDATE_THUMB, position, 0, video) );
        }
        
        messageHandler.sendMessage( Message.obtain(messageHandler, MSG_UPDATE_THUMBS) );
        //messageHandler.sendMessage(Message.obtain(messageHandler, MSG_LIST_COMPLETE));
        
	}
    
}
